package com.woorigil.social.worker.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.woorigil.social.domain.deal.Deal;
import com.woorigil.social.domain.deal.DealDao;
import com.woorigil.social.domain.deal.ManageStatus;
import com.woorigil.social.domain.point.DealPoint;
import com.woorigil.social.domain.point.DealPointDao;

@Component
public class DealSaveProcessor {
	private static Logger log = LoggerFactory.getLogger(DealSaveProcessor.class);
	
	@Autowired private DealDao dealDao;
	@Autowired private DealPointDao dealPointDao;
	
	public void process(Deal newDeal) {
		try {
			Deal oldDeal = dealDao.selectByMetaId(newDeal.getProviderCode(), newDeal.getMetaId());
			saveDeal(oldDeal, newDeal);
			saveDealPoint(oldDeal, newDeal);
		} catch (Exception e) {
			log.error("deal save error : " + newDeal.getProviderCode() + "-" + newDeal.getMetaId(), e);
		}
	}
	
	private int saveDeal(Deal oldDeal, Deal newDeal) {
		int dealId = 0;

		if (oldDeal != null) {
			dealId = oldDeal.getId();
			newDeal.setId(dealId);
			dealDao.update(newDeal);
		} else {
			dealId = dealDao.insert(newDeal);
			newDeal.setId(dealId);
		}
		return dealId;
	}

	private void saveDealPoint(Deal oldDeal, Deal newDeal) {
		DealPoint oldDealPoint = dealPointDao.selectByDealId(newDeal.getId());
		if (oldDealPoint != null) {
			int saleAverage = computeSaleAverage(oldDeal, newDeal);
			oldDealPoint.setSaleAverage(saleAverage);
			oldDealPoint.setManageStatus(ManageStatus.S);
			dealPointDao.update(oldDealPoint);
		} else {
			//최초 등록상품의 경우 평균판매가를 무조건 0으로 넣는다. (위메프가 판매 수량을 후려침)
			dealPointDao.insert(new DealPoint(newDeal.getId(), newDeal.getProviderCode(), 0, ManageStatus.S));
		}
	}
	
	private int computeSaleAverage(Deal oldDeal, Deal newDeal) {
		int oldNowCount = (oldDeal == null)? 0 : oldDeal.getNowCount();
		int saleCount = newDeal.getNowCount() - oldNowCount;
		return saleCount * newDeal.getSalesPrice();
	}	
}
